package com.minivision.sdktestdemo.ui;

import android.Manifest;
import android.app.ActivityManager;
import android.app.SearchManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.View;
import android.view.WindowManager;

import com.minivision.sdktestdemo.R;
import com.minivision.sdktestdemo.bean.MusicBean;
import com.minivision.sdktestdemo.controler.ui.activity.MusicMiniPlayControler;
import com.minivision.sdktestdemo.controler.ui.activity.MusicSearchControler;
import com.minivision.sdktestdemo.controler.ui.activity.NavControler;
import com.minivision.sdktestdemo.event.DataModificationEvent;
import com.minivision.sdktestdemo.event.PlayMusicEvent;
import com.minivision.sdktestdemo.model.MusicProvider;
import com.minivision.sdktestdemo.model.Provider;
import com.minivision.sdktestdemo.service.MusicService;
import com.minivision.sdktestdemo.theme.utils.ThemeUtils;
import com.minivision.sdktestdemo.utils.AlertDialogUtils;
import com.minivision.sdktestdemo.utils.LoadingWindowUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.LinkedList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import dalvik.system.DexClassLoader;
import dalvik.system.PathClassLoader;

public class StartActivity extends AppCompatActivity
        implements MusicListFragment.OnFragmentInteractionListener,
        ClassfiedInfoFragment.OnFragmentInteractionListener,
        MusicControlHandler.onProgressUpdated, MusicMiniPlayControler.PlayListGetter,
        MusicNavFragment.ToolBarHelper, MusicSearchControler.SearchHelper {

    @Override
    public Toolbar getToolbar() {
        return mToolbar;
    }

    public static final String PLAYING_MUSIC = "playing_music";

    private static final int MUSIC_DATA_PERMISSION = 2;
    private MusicService mService;
    private MusicMiniPlayControler mMiniPlayControler;
    private MusicSearchControler mSearchControler;
    private PlayMusicEvent mEvent;
    private LinkedList<Fragment> mFragments;

    private NavControler mNavControler;

    private Fragment mNowFragment;

    @Bind(R.id.tool_bar)
    Toolbar mToolbar;

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = ((MusicService.LocalBinder) service).getService();
            mService.initEvent();
            mService.setHandler(new MusicControlHandler(StartActivity.this));
            //初始化音乐控制器的界面
            if (mEvent == null) {
                mEvent = mService.getPlayingMusic();
            } else {
                mEvent.setPlayEvent(mService.getPlayingMusic());
            }
            mMiniPlayControler.init(mEvent);
            if (mNowFragment != null &&  mNowFragment instanceof OnFragmentUpdatedListener) {
                ((OnFragmentUpdatedListener)mNowFragment).update(mEvent);
            }
            if (mService.getPlayingMusic() != null
                    && mService.getPlayingMusic().mStatus == PlayMusicEvent.PLAY) {
                mService.startUpdate();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
        }
    };

    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int check = ContextCompat.checkSelfPermission(StartActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (check != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.DISABLE_KEYGUARD}, MUSIC_DATA_PERMISSION);
            } else {
                startService(new Intent(this, MusicService.class));
                bindService();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case MUSIC_DATA_PERMISSION:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startService(new Intent(this, MusicService.class));
                    bindService();
                } else {
                    finish();
                }
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        ButterKnife.bind(this);
        initData();
        initView();
        ThemeUtils.loadTheme(this);
    }


    private void initData() {
        MusicProvider.getInstance(this);
        mFragments = new LinkedList<>();
        mMiniPlayControler = new MusicMiniPlayControler(this);
        mSearchControler = new MusicSearchControler(this);
        mNavControler = new NavControler(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void play(PlayMusicEvent event) {
        if (mEvent == null) {
            mEvent = event;
        } else {
            mEvent.setPlayEvent(event);
        }
        if (event.mStatus == PlayMusicEvent.PLAY && mService != null) {
            mService.startUpdate();
        }
        mMiniPlayControler.updateView(event);
        OnFragmentUpdatedListener listener = (OnFragmentUpdatedListener) mNowFragment;
        listener.update(mEvent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        mToolbar.setTitle(getResources().getString(R.string.music));
        mToolbar.setNavigationIcon(R.drawable.ic_action_list_white);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mNavControler.show();
            }
        });
        mSearchControler.initMenuListener(menu);
        return super.onCreateOptionsMenu(menu);
    }

    public void switchFragment(Fragment to) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.hide(mNowFragment);
        if (!to.isAdded()) {
            fragmentTransaction.add(R.id.content_container, to, null);
        } else {
            fragmentTransaction.show(to);
        }
        fragmentTransaction.commit();
        mFragments.add(mNowFragment);
        mNowFragment = to;
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onModify(DataModificationEvent event) {
        if (event.mAction == DataModificationEvent.ACTION_LIST_CLEAR) {
            Provider.setAllChanged(MusicProvider.getInstance(this));
        }
        mMiniPlayControler.updateView(event);
        OnFragmentUpdatedListener listener = (OnFragmentUpdatedListener) getSupportFragmentManager().findFragmentById(R.id.content_container);
        listener.update(event);
    }

    private void initView() {
        setSupportActionBar(mToolbar);
        //初始化音乐列表
        initContentView(getSupportFragmentManager());
    }

    public static final String NAV_FRAGMENT = "nav";
//    public static final String LIST_FRAGMENT = "list";

    private void initContentView(FragmentManager fragmentManager) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        MusicNavFragment fragment = MusicNavFragment.newInstance(4, "test2");
        fragmentTransaction.add(R.id.content_container, fragment, NAV_FRAGMENT);
        fragmentTransaction.commit();
        mNowFragment = fragment;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode != NavControler.REQUEST) {
            updateMusicStatus();
        } else {
            ThemeUtils.changeTheme(this);
        }
    }

    public void bindService() {
        bindService(new Intent(this, MusicService.class), mServiceConnection, Context.BIND_AUTO_CREATE);
    }

    public void unbindService() {
        unbindService(mServiceConnection);
    }



    @Override
    protected void onStart() {
        requestPermission();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        super.onStart();
    }

    @Override
    protected void onStop() {
        unbindService();
        EventBus.getDefault().unregister(this);
        LoadingWindowUtils.release();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        AlertDialogUtils.release();
        super.onDestroy();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        handleIntent(intent);
    }

    public void handleIntent(Intent intent) {
        if (intent.getAction() == Intent.ACTION_SEARCH) {
            String query = intent.getStringExtra(SearchManager.QUERY);
        }
    }

    @Override
    public void onClick(String title, List<MusicBean> list) {
        MusicListFragment musicListFragment = MusicListFragment.newInstance(title, true);
        switchFragment(musicListFragment);
        musicListFragment.setEvent(mEvent);
        musicListFragment.setListBean(list);
    }

    public void turnToDetailActivity() {
        //设置切换动画
        Intent intent = new Intent(this, MusicPlayActivity.class);
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
        startActivityForResult(intent, 1);
    }

    @Override
    public void checkDetailActivity() {
        turnToDetailActivity();
    }

    @Override
    public void onClickEditList(List<MusicBean> list) {
        mMiniPlayControler.dismiss();
        MusicEditFragment musicEditFragment = MusicEditFragment.newInstance("", "");
        switchFragment(musicEditFragment);
        musicEditFragment.setListBean(list);
    }

    @Override
    public void update(int value, int max) {
        mMiniPlayControler.update(mEvent, value, max);
    }

    @Override
    public void startUpdate() {
        if (mService != null) {
            mService.startUpdate();
        }
    }

    @Override
    public void stopUpdate() {
        if (mService != null) {
            mService.stopUpdate();
        }
    }

    public void updateMusicStatus() {
        mMiniPlayControler.update();
        OnFragmentUpdatedListener listener = (OnFragmentUpdatedListener) mNowFragment;
        listener.update(mEvent);
    }

    @Override
    public List<MusicBean> getPlayList() {
        if (mService != null) {
            return mService.getPlayList();
        }
        return null;
    }

    @Override
    public void onBackPressed() {
        Fragment preFragment = mFragments.pollLast();
        if (preFragment != null) {
            switchFragment(preFragment);
            updateMusicStatus();
            mFragments.pollLast();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void beginSearch() {
        SearchResultFragment searchResultFragment = SearchResultFragment.newInstance("", "");
        searchResultFragment.setBeanList(mService.getPlayList());
        switchFragment(searchResultFragment);
    }

    @Override
    public void endSearch() {
        Provider.setAllChanged(MusicProvider.getInstance(this));
        onBackPressed();
    }

    @Override
    public void doSearch(String text) {
        if (mNowFragment instanceof MusicSearchControler.SearchResult) {
            MusicSearchControler.SearchResult searchResult = (MusicSearchControler.SearchResult) mNowFragment;
            searchResult.updateSearchResult(text);
        }
    }
}

